package ncut.shumei.service.impl;

import ncut.shumei.dao.ElevatorDao;
import ncut.shumei.dao.MaintenanceTaskDao;
import ncut.shumei.dao.TaskCommentDao;
import ncut.shumei.dao.UserDao;
import ncut.shumei.dto.*;
import ncut.shumei.entity.Elevator;
import ncut.shumei.entity.MaintenanceTask;
import ncut.shumei.entity.TaskComment;
import ncut.shumei.entity.User;
import ncut.shumei.exception.BusinessException;
import ncut.shumei.service.MaintenanceTaskService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class MaintenanceTaskServiceImpl implements MaintenanceTaskService {

    @Autowired
    private MaintenanceTaskDao taskDao;
    
    @Autowired
    private TaskCommentDao commentDao;
    
    @Autowired
    private ElevatorDao elevatorDao;
    
    @Autowired
    private UserDao userDao;

    @Override
    public List<MaintenanceTaskDTO> getTasks(String status, Integer elevatorId, Integer maintainerId) {
        return taskDao.findAll(status, elevatorId, maintainerId).stream()
                .map(this::convertToDTO)
                .collect(Collectors.toList());
    }

    @Override
    public MaintenanceTaskDTO getTask(Integer id) {
        MaintenanceTask task = taskDao.findById(id);
        if (task == null) {
            throw new BusinessException("维护任务不存在");
        }
        return convertToDTO(task);
    }

    @Override
    @Transactional
    public MaintenanceTaskDTO createTask(MaintenanceTaskCreateRequest request) {
        // 验证电梯和维护人员是否存在
        Elevator elevator = elevatorDao.findById(request.getElevatorId());
        User maintainer = userDao.findById(request.getMaintainerId());
        if (elevator == null) {
            throw new BusinessException("电梯不存在");
        }
        if (maintainer == null || !"MAINTAINER".equals(maintainer.getRole())) {
            throw new BusinessException("维护人员不存在");
        }
        
        MaintenanceTask task = new MaintenanceTask();
        BeanUtils.copyProperties(request, task);
        task.setStatus("PENDING");
        
        taskDao.insert(task);
        return convertToDTO(task);
    }

    @Override
    @Transactional
    public MaintenanceTaskDTO updateTask(Integer id, MaintenanceTaskCreateRequest request) {
        MaintenanceTask task = taskDao.findById(id);
        if (task == null) {
            throw new BusinessException("维护任务不存在");
        }
        
        BeanUtils.copyProperties(request, task);
        taskDao.update(task);
        return convertToDTO(task);
    }

    @Override
    @Transactional
    public void deleteTask(Integer id) {
        MaintenanceTask task = taskDao.findById(id);
        if (task == null) {
            throw new BusinessException("维护任务不存在");
        }
        taskDao.deleteById(id);
    }

    @Override
    @Transactional
    public void updateTaskStatus(Integer id, String status, Integer userId) {
        MaintenanceTask task = taskDao.findById(id);
        if (task == null) {
            throw new BusinessException("维护任务不存在");
        }
        
        taskDao.updateStatus(id, status);
        
        // 如果任务完成，更新电梯的维护日期
        if ("COMPLETED".equals(status)) {
            elevatorDao.updateMaintenanceDate(task.getElevatorId(), LocalDateTime.now().toLocalDate());
        }
    }

    @Override
    @Transactional
    public void addComment(Integer taskId, String content, Integer userId) {
        MaintenanceTask task = taskDao.findById(taskId);
        if (task == null) {
            throw new BusinessException("维护任务不存在");
        }
        
        TaskComment comment = new TaskComment();
        comment.setTaskId(taskId);
        comment.setUserId(userId);
        comment.setContent(content);
        
        commentDao.insert(comment);
    }

    private MaintenanceTaskDTO convertToDTO(MaintenanceTask task) {
        MaintenanceTaskDTO dto = new MaintenanceTaskDTO();
        BeanUtils.copyProperties(task, dto);
        
        // 设置电梯信息
        Elevator elevator = elevatorDao.findById(task.getElevatorId());
        if (elevator != null) {
            ElevatorDTO elevatorDTO = new ElevatorDTO();
            BeanUtils.copyProperties(elevator, elevatorDTO);
            dto.setElevator(elevatorDTO);
        }
        
        // 设置维护人员信息
        User maintainer = userDao.findById(task.getMaintainerId());
        if (maintainer != null) {
            UserDTO maintainerDTO = new UserDTO();
            BeanUtils.copyProperties(maintainer, maintainerDTO);
            dto.setMaintainer(maintainerDTO);
        }
        
        // 设置评论列表
        List<TaskComment> comments = commentDao.findByTaskId(task.getId());
        dto.setComments(comments.stream()
                .map(c -> {
                    TaskCommentDTO commentDTO = new TaskCommentDTO();
                    BeanUtils.copyProperties(c, commentDTO);
                    return commentDTO;
                })
                .collect(Collectors.toList()));
        
        return dto;
    }
} 